package concurrency.chapter11;

/**
 * 31讲-如何给你的应用程序注入钩子程序
 */
//!javac
//javac ExitCapture.java
//rm -rf nohup.out
//java -cp ExitCapture
//jps
//kill 8487
//用kill -9 8509 不会捕获应用程序停止的信号
public class ExitCapture {
    public static void main(String[] args) {

        Runtime.getRuntime().addShutdownHook(
                new Thread(() -> {
                    System.out.println("The application will be exit.");
                    nottifyAdnRelease();
                })
        );

        int i = 0;
        while (true) {
            try {
                Thread.sleep(1_000L);
                System.out.println("I am working...");
            } catch (Throwable e) {
                e.printStackTrace();
            }
            i++;
            if (i > 10)
                throw new RuntimeException("error");
        }
    }

    private static void nottifyAdnRelease() {
        System.out.println("notify to the admin.");
        try {
            Thread.sleep(1_000);
        } catch (InterruptedException e) {
        }
        System.out.println("will release resource(socket,file,connection)");
        try {
            Thread.sleep(1_000);
        } catch (InterruptedException e) {
        }
        System.out.println("Release and Notify Done.");

    }
}
